package com.kkb.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kkb.mapper.MenuMapper;
import com.kkb.mapper.RoleMenuMapper;
import com.kkb.pojo.Menu;
import com.kkb.pojo.MenuExample;
import com.kkb.pojo.RoleMenu;
import com.kkb.pojo.RoleMenuExample;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Lxy
 * @create 2022-03-22 0:58
 */

@Service
public class ResourceService {
    @Resource
    private MenuMapper menuMapper;
    @Transactional(propagation = Propagation.REQUIRED,readOnly = true)
    public PageInfo<Menu> getMenuList(int pageNum, int pageSize,String ResourceName){
        MenuExample menuExample = new MenuExample();
        MenuExample.Criteria criteria = menuExample.createCriteria();
        criteria.andM_nameLike("%"+ResourceName+"%");
        PageHelper.startPage(pageNum,pageSize);
        List<Menu> menuList = menuMapper.selectByExample(menuExample);
        return new PageInfo<>(menuList);
    }


    @Transactional(propagation = Propagation.REQUIRED,readOnly = true)
    public Menu getMenuById(int m_id){
        Menu menu = menuMapper.selectByPrimaryKey(m_id);
        return menu;
    }

    //验证菜单的唯一性
    //0表示菜单名字不变，-1表示修改后的菜单名字存在同名，1表示可以修改
    @Transactional(propagation = Propagation.REQUIRED,readOnly = true)
    public int validateMenuName(int m_id, Menu updateMenu){
        //名字不变，返回true表示名字肯定是唯一的
        Menu menu = menuMapper.selectByPrimaryKey(m_id);
        String m_name = menu.getM_name();
        System.out.println(m_name);
        if (updateMenu.getM_name().equals(m_name)){
            return 0;
        }
        MenuExample menuExample = new MenuExample();
        MenuExample.Criteria criteria = menuExample.createCriteria();
        criteria.andM_nameEqualTo(updateMenu.getM_name());
        List<Menu> menuList = menuMapper.selectByExample(menuExample);
        //如果menuList的长度大于1，说明在修改过m_name后与数据库有同名的
        if (menuList.size() > 0){
            return -1;
        }
        return 1;
    }

    //判断状态码是否变化
    //0表示状态码不变，1表示状态码修改
    @Transactional(propagation = Propagation.REQUIRED,readOnly = true)
    public int validateState(int m_id,Menu updateMenu){
        Menu menu = menuMapper.selectByPrimaryKey(m_id);
        Integer m_state = menu.getM_state();
        if (updateMenu.getM_state().equals(m_state)){
            return 0;
        }
        return 1;
    }

    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = {Exception.class})
    //更新的名字和状态
    public int updateMenu(Menu updateMenu){
        return menuMapper.updateByPrimaryKeySelective(updateMenu);
    }
}
